package chixing.day19;

public class PublicResource {
    private int number;
    public PublicResource(){}
    public PublicResource(int number) {
        this.number = number;
    }

    //生产一个面包
    public synchronized void produce(){
        System.out.println("生产者抢占到了 1111111111111111111");
        if(number ==10){
            System.out.println("生产者抢占到了，面包个数number =" + number + "不生产，进入等待队列");
            try {
                this.wait(); // 生产者不生产，进入等待队列，
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else{
            number++;
            this.notify();// 唤醒在等待队列的消费者，来消费
            System.out.println("-----生产者生产了1个面包，number = " + number);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

    }

    //消费一个面包
    public synchronized void consume(){
        System.out.println("消费者抢占到了 222222222222222222");
        if(number ==0){
            System.out.println("消费者抢占到了，面包个数number =" + number + "不消费，进入等待队列");
            try {
                this.wait(); // 消费者不消费，进入等待队列
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }else{
            number --;
            this.notify();// 唤醒生产者线程来生产面包
            System.out.println("---------------消费者消费了一个面包， number = " + number);
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
    }

}
